const express = require('express')
const cors = require('cors')
const config = require('./config/config.default')
const http = require('http')
// 引入数据库连接
require('./db')

const errorHandler = require('./middleware/errorHandler') // 确保路径正确
const routes = require('./router')  // 确保路径正确指向你的router目录
const ChatServer = require('./socket/chatServer')
const uploadRouter = require('./router/upload')

// 加一个注释，用以说明，本项目代码可以任意定制更改
const app = express()
const server = http.createServer(app)

// 修改 CORS 配置
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));

// 添加额外的 headers
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Credentials', 'true');
  next();
});

// 初始化聊天服务器
const chatServer = new ChatServer(server)

// 中间件
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// 添加静态文件服务
app.use('/uploads', express.static('public/uploads'))

// 挂载路由
app.use('/api', routes)
app.use('/api/upload', uploadRouter)

// 挂载统一处理服务端错误中间件
app.use(errorHandler)

const PORT = 3000
server.listen(PORT, () => {
  console.log(`Server is running at ${config.baseUrl}`)
})
